const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
var QR = require("../../utils/qrcode.js");
var QRCode = require('../../utils/weapp-qrcode.js')
var that;
var timer = null;
var qrcode;
//获取应用实例
const app = getApp()
Page({
  data: {
    userInfo: {},
    isAuthBaseInfo: false,
    showDialog: false,
    unitName: "", 
    houseName: "", 
    contractPhoto: "",
    isUpdate:false,
    isCert:false,
    qrHidden:true,
    maskHidden:true,
    canvasHidden: false,
    imagePath: '',
    isBindMP:false, //是否开通公众号推送
    placeholder: '',//默认二维码生成文本
    doorQrCacheKey:'', //开门扫码二维码缓存key
  },
  getIndexData: function () {
    that.setData({
      userInfo: app.globalData.userInfo
    });
    return app.post(api.IndexUrl, { retry: 3, isAllow: true }).then(rsp => {
      if (rsp) {
        if (rsp.pre) {
          that.setData({
            unitName: rsp.unitName,
            houseName: rsp.houseName,
            contractPhoto: rsp.contractPhoto,
          });
          app.globalData.ownersNo = rsp.homeownersNo;
          //已经入住
          wx.setStorageSync('isTouristRent', true);
          app.isTouristRent = true;
        } else {
          that.setData({
            unitName: '',
            houseName: '',
            contractPhoto: '',
          });
          app.globalData.ownersNo = '';
          //已经入住
          wx.setStorageSync('isTouristRent', false);
          app.isTouristRent = false;
        }
      }
      return Promise.resolve(true);
    }).catch((err) => {
      console.log('err', err);
      return Promise.reject(err);
    });
  },
  checkIsCert(){ //检测是否实名认证
    if(!app.globalData.isCert){
      util.confirm.modal('您还未办理实名认证,请前去办理！', '温馨提示', function () {
        wx.navigateTo({
          url: '/pages/faceAuth/index',
        })
      });
      return false;
    }
    wx.navigateTo({
      url: '/pages/checkin/index',
    })
    return true;
  },
  onLoad: function (options) {
    that = this;
    that._initQr();
    that.setData({
      isCert: app.globalData.isCert
    });
    if (options.finish) {
      wx.navigateBack({
        delta: 1
      });
    }else{
      that.setData(app.globalData);
      if (app.globalData.hasLogin) {
        that.getIndexData();
      } else {
        if (!that.isTouristRent) {
          util.confirm.modal('您还未办理入住或房东还未为您系统登记,请您尽快与房东联系', '温馨提示', function () {
            if(!app.globalData.hasLogin){
              wx.navigateTo({
                url: '/pages/auth/login/autoLogin',
              })
            }
          });
        }
      }
    }
  },
  _initQr(){
    var size = that.setCanvasSize(400);
    qrcode = new QRCode('mycanvas', {
      // usingIn: this,
      text: "",
      width: size.w,
      height: size.h,
      colorDark: "#1CA4FC",
      colorLight: "white",
      correctLevel: QRCode.CorrectLevel.H,
    });
  },
  setOpenPush(e){
    util.login().then((ress) => {
      wx.getUserInfo({
        withCredentials: true,
        success: function (res) {
          res.code = ress.code;
          that.setData({
            isAuthUserInfo: false
          });
          app.post(api.OpenPush, res).then((rsp) => {
            if (rsp.isBindMP){
              util.toast.success('开通成功！');
            }else{
              wx.navigateTo({
                url: '/pages/index/web?url=' + encodeURIComponent(rsp.qrTxt),
              })
              /*
              that.setData({
                placeholder: rsp.qrTxt
              });
              that.createQr();*/
              /*
              that.setData({
                qrHidden: true,
                maskHidden: true
              });
              util.toast.loading('生成中......');
              var st = setTimeout(function () {
                wx.hideToast()
                qrcode.makeCode(rsp.qrTxt);
                qrcode.exportImage(function (path) {
                  that.setData({
                    imagePath:path
                  });
                })
                that.setData({
                  qrHidden: false,
                  maskHidden: false,
                });
                clearTimeout(st);
              }, 200)*/
            }
          });
        }
      })
    }).catch((err) => {
      console.log("未登录报异常：", err);
    });
  },
  checkMpOp(){
    app.post(api.CheckOpenPush).then((rsp) => {
      if (!util.isNullOrEmpty(rsp.isBindMP)) {
        that.setData({
          isBindMp: rsp.isBindMP,
          showDialog: false
        });
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  openMpPush(){
    if (that.data.isBindMp) return false;
    var checkTimes = 3;
    app.post(api.OpenPush).then((rsp) => {
      if (!util.isNullOrEmpty(rsp.isBindMP)) {
        if (!rsp.isBindMP) {
          wx.navigateTo({
            url: './web?url=' + rsp.qrTxt,
          })
        } else {
          that.setData({
            isBindMp: rsp.isBindMP,
            showDialog: false
          });
        }
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  closeDialog(){
    that.setData({
      showDialog: false
    });
  },
  checkOpenPush() {
    if (that.data.isBindMp) return false;
    that.data.isUpdate = true;
    app.post(api.CheckOpenPush).then((rsp) => {
      if (rsp.isBindMP) {
        util.toast.success('开通成功！');
        that.setData({
          isBindMp: true,
          showDialog: false
        });
      } else {
        //弹框提示前往开通推送
        that.setData({
          isBindMp:false,
          showDialog:true
        });
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  closeImgBox(){
    that.setData({
      maskHidden: !that.data.maskHidden,
      qrHidden: true,
    });
    //that.destroyDoorQr();
  },
  // 长按保存
  save: function () {
    wx.showActionSheet({
      itemList: ['保存图片'],
      success: function (res) {
        if (res.tapIndex == 0) {
          that.savePicture(that.data.imagePath);
        }
      }
    })
  },
  downLoad(path) {
    wx.saveImageToPhotosAlbum({
      filePath: path,
      success: function (ret) {
        wx.showToast({ title: '保存图片成功' });
        //util.confirm.modal(res.path);
      },
      fail: function (ret) {
        util.toast.fail('保存图片失败');
        //util.confirm.modal(res.path);
      }
    })
  },
  // 点击保存图片
  savePicture: function (path) {
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          that.downLoad(path);
        } else {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序使用
              that.downLoad(path);
            },
            fail: function () {
              /*获取权限时点击了拒绝以后的弹窗*/
              if (wx.canIUse('button.open-type.openSetting')) {
                wx.showModal({
                  title: '温馨提示',
                  content: '您未授权，将无法正常使用保存图片或视频的功能体验，请点击重新授权进入开启授权。',
                  confirmText: '重新授权',
                  cancelText: '取消',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: function (data) {
                          if (data.authSetting["scope.writePhotosAlbum"] == true) {
                            util.toast.success('授权成功');
                            that.downLoad(path);
                          } else {
                            util.toast.fail('授权失败');
                          }
                        }
                      })
                    }
                  }
                })
              } else {
                wx.showModal({
                  title: '温馨提示',
                  content: '您未授权，将无法正常使用保存图片或视频的功能体验，请删除小程序重新进入。'
                })
              }
            }
          })
        }
      }
    })
  },
  createQr: function () {
    that.setData({
      qrHidden: true,
      maskHidden: true
    });
    util.toast.loading('生成中......');
    var st = setTimeout(function () {
      wx.hideToast()
      var size = that.setCanvasSize(520);
      //绘制二维码
      that.createQrCode(that.data.placeholder, "mycanvas", size.w, size.h);
      that.setData({
        qrHidden: false,
        maskHidden: false,
      });
      clearTimeout(st);
    }, 2000)

  },
  checkIsAuthUserInfo(){
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            isAuthUserInfo:false
          });
        } else {
          that.setData({
            isAuthUserInfo: true
          });
        }
      }
    });
  },
  openPush(e){
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权
          that.setOpenPush();
        }else{
          /*获取权限时点击了拒绝以后的弹窗*/
          if (wx.canIUse('button.open-type.openSetting')) {
            wx.showModal({
              title: '温馨提示',
              content: '您未授权，将无法正常使用推送，请点击重新授权进入开启授权。',
              confirmText: '重新授权',
              cancelText: '取消',
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userInfo"] == true) {
                        util.toast.success('授权成功');
                        that.setOpenPush();
                      } else {
                        util.toast.fail('授权失败');
                      }
                    }
                  })
                }
              }
            })
          } else {
            wx.showModal({
              title: '温馨提示',
              content: '您未授权，将无法推送设置。'
            })
          }
        }
      }
    });
  },
  onPullDownRefresh() {
    that.setData({
      unitName: "",
      houseName: "",
      contractPhoto: ""
    });
    that.getIndexData().then(rsp => {
      that.checkMpOp(); //检测公众号推送
    }).catch(err => {
      console.log('xxxxxxxxxxxx');
    });
    wx.stopPullDownRefresh();
  },
  previewImage: function (e) {
    let contractPhoto = that.data.contractPhoto;
    if (contractPhoto.indexOf('/') != -1){
      var tmp = contractPhoto.split(',').map(function(i,n){
        return app.showImg(i);
      });
      wx.previewImage({
        current: tmp[0], // 当前显示图片的http链接
        urls: tmp // 需要预览的图片http链接列表
      })
    }else{
      util.confirm.modalOk('合同不存在');
    }
  },
  scanCode(){
    //弹出二维码被扫开门
    /*
    that.setData({
      placeholder: "123"
    });
    that.createQr();*/
    app.postPureForm(api.GetControlDoorQR).then(rsp => {
      if (rsp.key){
        that.setData({
          placeholder: rsp.key,
          doorQrCacheKey: rsp.key
        });
        that.createQr();
      }
    }).catch((err) => {
      console.log('err', err);
    });
    /*
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log('qrcode', res)
        that.authLocation(res.result);
      },
      fail(res) {
        console.log('qrcodefail', res)
        util.toast.fail('扫码失败');
      }
    })*/
  },
  authLocation(flag) {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则门禁无法使用',
            success: function (res) {
              if (res.cancel) {
                console.info("1授权失败返回数据");
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      util.toast.success('授权成功');
                      wx.getLocation({
                        type: 'wgs84',
                        success: function (res) {
                          var latitude = res.latitude
                          var longitude = res.longitude
                          var location = latitude + ',' + longitude;
                          that.openDoor(flag, location);
                        }
                      })
                    } else {
                      util.toast.fail('授权失败');
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.getLocation({
            type: 'wgs84',
            success: function (res) {
              var latitude = res.latitude
              var longitude = res.longitude
              var location = latitude + ',' + longitude;
              that.openDoor(flag, location);
            },
            fail(res){
              util.confirm.modalOk('授权失败,无法使用门禁');
            }
          })
        }
      }
    })
  },
  openDoor(flag, location) {
    util.toast.loading('门禁开锁中......');
    return app.postPureForm(api.OpenControlDoor, { flag: flag }).then(rsp => {
      return that.savePosition(location);
    }).catch((err) => {
      console.log('err', err);
    });
  },
  savePosition(location){ //提交当前定位信息
    return app.postPure(api.SavePoi, { location: location, mobile: app.globalData.phoneNumber });
  },
  getUserInfo(e) {
    if (e.detail.userInfo == undefined) {
      util.toast.fail('微信授权失败');
      return;
    }
    util.login().then((res) => {
      let baseInfo = e.detail;
      baseInfo.phoneNumber = app.globalData.phoneNumber;
      baseInfo.code = res.code;
      baseInfo.isAllow = true;
      //保存用户的基本信息
      app.post(api.SaveBaseInfo, baseInfo, { retry: 1}).then(res => {
        e.detail.userInfo.nickName = Base64.decode(e.detail.userInfo.nickName);
        app.globalData.userInfo = e.detail.userInfo;
        wx.setStorageSync('userInfo', e.detail.userInfo);
        app.globalData.isAuthBaseInfo = true;
        wx.setStorageSync('isAuthBaseInfo', true);
        that.setData({
          isAuthBaseInfo: true,
          userInfo: e.detail.userInfo
        });
      }).catch((err) => {
        console.log('err', err);
      });
    }).catch((err) => {
      console.log("未登录报异常：", err);
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    if (that.data.isUpdate) {
      that.setData({ isUpdate: false, isCert: app.globalData.isCert});
      that.getIndexData().then(rsp => {
        if (that.data.isBindMp) return false;
        that.checkMpOp(); //检测推送开通
      }).catch(err => {
        console.log('xxxxxxxxxxxx');
      });
    }
    that.checkIsAuthUserInfo();
  },
  destroyDoorQr(){ //开门二维码销毁
    if(util.isNullOrEmpty(that.data.doorQrCacheKey))return false;
    // 页面隐藏
    app.postPureForm(api.DestroyControlDoorQR, { key : that.data.doorQrCacheKey}).then(rsp => {
        that.setData({
          doorQrCacheKey:''
        });
    }).catch((err) => {
      console.log('err', err);
    });
  },
  onHide: function () {
    //that.destroyDoorQr();
    if (timer) clearInterval(timer);
  },
  onUnload: function () {
    // 页面关闭
    //that.destroyDoorQr();
    if (timer) clearInterval(timer);
  },
  exitRoom(){ //退房
    util.confirm.openExt('您确定好要申请退房了吗?', function () {
      app.post(api.ExitRoom).then((rsp)=>{
        util.confirm.modal('退房申请成功,请耐心等待房东的确认！', '注意' , ()=>{
              wx.navigateTo({
                url: '/pages/notice/list/list',
              })
         });
      });
    });
  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function (w = 686) {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / w;//不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width;//canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(url, canvasId, cavW, cavH);
    setTimeout(() => { that.canvasToTempImage(); }, 1000);

  },
  //获取临时缓存照片路径，存入data中
  canvasToTempImage: function () {
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        that.setData({
          imagePath: tempFilePath,
          // canvasHidden:true
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //点击图片进行预览，长按保存分享图片
  previewImg: function (e) {
    var img = that.data.imagePath;
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  exitLogin: function () {
    wx.showModal({
      title: '',
      confirmColor: '#b4282d',
      content: '注销？',
      success: function (res) {
        if (res.confirm) {
          wx.clearStorage();
          wx.navigateTo({
            url: '/pages/auth/login/autoLogin',
          })
        }
      }
    })
  }
})
